package com.hzdesk.media.koreabatchmatvector.logic.view;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.hzdesk.media.koreabatchmatvector.R;
import com.hzdesk.media.koreabatchmatvector.base.MyClientApplication;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/7/10.
 * 杭州席媒科技有限公司  Developers  刘传华  10
 * 佛祖镇楼 bug辟易
 */

public class AgreementActivity extends AppCompatActivity {
    @BindView(R.id.activity_agreement_progress)
    ProgressBar activityAgreementProgress;
    @BindView(R.id.activity_agreement_webview_01)
    WebView activityAgreementWebview_01;
    @BindView(R.id.activity_agreement_lin)
    LinearLayout activityAgreementLin;
    private WebSettings webSettings;
    private int webview_pager;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hookWebView();
        setContentView(R.layout.activity_agreement);
        ButterKnife.bind(this);
        initDate();
    }

    private void initDate() {
        webview_pager = getIntent().getIntExtra("webview_pager", 0);
        webSettings = activityAgreementWebview_01.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);                                                       //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true);                                                  // 缩放至屏幕的大小
        webSettings.setDisplayZoomControls(true);                                                   //隐藏原生的缩放控件
        webSettings.setAllowFileAccess(true);                                                       //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);                                 //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true);                                              //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");                                            //设置编码格式

        //开启DOM storage API功能
        webSettings.setDomStorageEnabled(true);
        //开启database storage API功能
        webSettings.setDatabaseEnabled(true);
        //开启Application Cache功能
        webSettings.setAppCacheEnabled(true);
        // isNetworkConnect(webview_pager);
        loadLocalPager(webview_pager);
        activityAgreementWebview_01.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
               // showErrorPage();//显示错误页面
                loadLocalPager(webview_pager);
            }
        });
        activityAgreementWebview_01.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    activityAgreementProgress.setVisibility(View.VISIBLE);
                    activityAgreementProgress.setProgress(newProgress);
                } else {
                    activityAgreementProgress.setVisibility(View.GONE);
                }
            }
        });

    }

    // 判断网络有没有 有加载网络页面，没有就加载本地页面
    private void isNetworkConnect(int webview_pager) {
        ConnectivityManager mCm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mCm.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        NetworkInfo MYetworkInfo = mCm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mNetworkInfo != null && mNetworkInfo.isConnected()) {
            loadNetWorkPager(webview_pager);
        } else if (MYetworkInfo != null && MYetworkInfo.isConnected()) {
            loadNetWorkPager(webview_pager);
        } else {
            loadLocalPager(webview_pager);
        }
    }

    private void loadLocalPager(int webview_pager) {
        switch (webview_pager) {
            case 0: //服务协议
                activityAgreementWebview_01.loadUrl("file:///android_asset/service.html");
                if(MyClientApplication.isIsNetWork()){
                    activityAgreementWebview_01.loadUrl("http://192.168.10.81:8080/html/protocal.html");
                }
                break;
            case 1: //版权信息
                activityAgreementWebview_01.loadUrl("file:///android_asset/copyrights.html");
                break;
            case 2:// 关于席媒
                activityAgreementWebview_01.loadUrl("file:///android_asset/about.html");
                break;
        }
    }

    private void loadNetWorkPager(int webview_pager) {
        switch (webview_pager) {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
        }
        activityAgreementWebview_01.loadUrl("http://www.baidu.com/");
    }

    /**
     * 显示自定义错误提示页面，用一个View覆盖在WebView
     */
    private void showErrorPage() {
//        View view = View.inflate(this,R.layout.webview_error,null);
//        activityAgreementWebview_01.removeAllViews(); //移除加载网页错误时，默认的提示信息
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
//        activityAgreementWebview_01.addView(view, 0, layoutParams); //添加自定义的错误提示的View
         }

        @Override
        protected void onResume () {
            super.onResume();
            activityAgreementWebview_01.onResume();
        }

        @Override
        protected void onPause () {
            super.onPause();
            activityAgreementWebview_01.onPause();
        }

        @Override
        public boolean onKeyDown ( int keyCode, KeyEvent event){
      /*  if ((keyCode == KEYCODE_BACK) && activityAgreementWebview_01.canGoBack()) {
            activityAgreementWebview_01.goBack();
            return true;
        }*/
            return super.onKeyDown(keyCode, event);
        }

        @Override
        protected void onDestroy () {
            if (activityAgreementWebview_01 != null) {
                activityAgreementWebview_01.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
                activityAgreementWebview_01.clearHistory();

                ((ViewGroup) activityAgreementWebview_01.getParent()).removeView(activityAgreementWebview_01);
                activityAgreementWebview_01.destroy();
                activityAgreementWebview_01 = null;
            }
            super.onDestroy();
        }

    public static void hookWebView() {
        int sdkInt = Build.VERSION.SDK_INT;
        try {
            Class factoryClass = Class.forName("android.webkit.WebViewFactory");
            Field field = factoryClass.getDeclaredField("sProviderInstance");
            field.setAccessible(true);
            Object sProviderInstance = field.get(null);
            if (sProviderInstance != null) {
                return;
            }
            Method getProviderClassMethod;
            if (sdkInt > 22) {
                getProviderClassMethod = factoryClass.getDeclaredMethod("getProviderClass");
            } else if (sdkInt == 22) {
                getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
            } else {
                return;
            }
            getProviderClassMethod.setAccessible(true);
            Class providerClass = (Class) getProviderClassMethod.invoke(factoryClass);
            Class delegateClass = Class.forName("android.webkit.WebViewDelegate");
            Constructor providerConstructor = providerClass.getConstructor(delegateClass);
            if (providerConstructor != null) {
                providerConstructor.setAccessible(true);
                Constructor declaredConstructor = delegateClass.getDeclaredConstructor();
                declaredConstructor.setAccessible(true);
                sProviderInstance = providerConstructor.newInstance(declaredConstructor.newInstance());
                field.set("sProviderInstance", sProviderInstance);
            }
        } catch (Throwable e) {
        }
    }

}
